<template>
  <div class="announcement-page">
    <!-- 页面标题 -->
    <div class="page-header" >
      <el-button @click="goBack" size="large" >
        <el-icon><ArrowLeft /></el-icon>返回
      </el-button>
      <h2>我的公告</h2>
    </div>

    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <el-button type="danger" @click="batchDelete" :disabled="selectedAnnouncements.length === 0">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>

      <div class="search-group">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索公告标题/发送人"
            class="search-input"
            @keyup.enter.native="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
          </template>
        </el-input>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 公告列表 -->
    <el-table
        v-loading="isLoading"
        :data="displayAnnouncements"
        stripe
        style="width: 100%"
        border
        v-if="messageItemStore.allAnnReceivers && messageItemStore.allAnnReceivers.length > 0"
    >
      <el-table-column type="selection" width="55" :selectable="selectableRow" />
      <!-- 自定义索引列，实现跨页延续的序号 -->
      <el-table-column label="序号" width="60">
        <template #default="{ row, $index }">
          {{ (currentPage - 1) * pageSize + $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="systemAnnouncement.messageTitle" label="消息标题" min-width="200">
        <template #default="{ row }">
          <span @click="viewAnnouncement(row)">{{ row.systemAnnouncement?.messageTitle }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="sender.name" label="发送人" min-width="120" />
      <el-table-column prop="readStatus" label="阅读状态" min-width="120">
        <template #default="{ row }">
          <el-tag size="large" :type="row.readStatus === 0 ? 'danger' : 'success'">
            {{ row.readStatus === 0 ? "未读" : "已读" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="systemAnnouncement?.publishTime"  label="发布时间" min-width="120">
        <template #default="{ row }">
          {{ formatDateTime(row.systemAnnouncement?.publishTime).display }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="viewAnnouncement(row)">查看</el-button>
          <el-button size="small" type="danger" @click="deleteAnnouncement(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-if="displayAnnouncements.length === 0 && !isLoading" description="暂无公告通知" />

    <!-- 分页导航 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalAnnouncements"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Delete } from '@element-plus/icons-vue';
import axios from "axios";
import { ElMessage, ElMessageBox } from 'element-plus';
import { userStore } from '/src/components/store/index.js';
import { messageStore } from '@/components/store/message.js';
import { formatDateTime } from '/src/utils/dateUtil.js';
import request from "@/utils/request.js";

// 状态管理
const messageItemStore = messageStore();
const userItemStore = userStore();
const router = useRouter();

// 本地状态
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalAnnouncements = ref(0);
const isLoading = ref(true);
const selectedAnnouncements = ref([]);

//返回上一页；
const goBack = () => {
  router.go(-1);
};

//序号；


// 计算属性：过滤后的公告列表（带分页）
const filteredAnnouncements = computed(() => {
  if (!messageItemStore.allAnnReceivers) return [];

  // 搜索过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase();
    return messageItemStore.allAnnReceivers.filter(item =>
        item.systemAnnouncement.messageTitle.toLowerCase().includes(keyword) ||
        item.sender.name.toLowerCase().includes(keyword)
    );
  }

  return messageItemStore.allAnnReceivers;
});

// 计算属性：当前页显示的公告
const displayAnnouncements = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredAnnouncements.value.slice(start, end);
});

// 行选择判断
const selectableRow = (row) => {
  return true; // 所有行都可选
};




// 加载公告数据
// 在loadAnnouncements中添加数据日志，查看实际返回结构
const loadAnnouncements = async () => {
  isLoading.value = true;
  try {
    const resp = await request.post(`/annReceiver/listForAnnReceiver/${userItemStore.user.id}`);
    console.log('公告数据结构', resp.data[0]); // 打印第一条数据查看结构
    messageItemStore.allAnnReceivers = resp.data;
    totalAnnouncements.value = filteredAnnouncements.value.length;
  } catch (error) {
    // 错误处理
  } finally {
    isLoading.value = false;
  }
};

// 查看公告详情
const viewAnnouncement = async (item) => {
  // 跳转到详情页
  // router.push(`/announcement/detail/${item.announcementId}`);
  // 发送方
  router.push({
    path: '/announcement/detail',
    query: {
      id: item.id,
      readStatus: item.readStatus,
      announcementId: item.announcementId,
      senderId: item.senderId,
      messageTitle: item.systemAnnouncement.messageTitle
      // 可以选择性地传递其他需要的字段
    }
  });
};

// 删除单个公告
const deleteAnnouncement = async (item) => {
  try {
    const confirm = await ElMessageBox.confirm(
        `确定要删除这条公告吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    if (confirm !== 'confirm') return;

    // 调用API删除
    await request.delete(`/annReceiver/deleteAnnReceiver/${item.announcementId}/${item.receiverId}`);

    // 更新本地状态
    const index = messageItemStore.allAnnReceivers.findIndex(
        ann => ann.id === item.id
    );
    if (index !== -1) {
      messageItemStore.allAnnReceivers.splice(index, 1);
      ElMessage.success('删除成功');

    // 移除选中状态
    selectedAnnouncements.value = selectedAnnouncements.value.filter(
        id => id !== item.id
    );
    }
    //重新拉取数据库信息
    loadAnnouncements();

  } catch (error) {
    ElMessage.error('删除失败，请重试');
  }
};

// 批量删除公告
const batchDelete = async () => {
  if (selectedAnnouncements.value.length === 0) {
    ElMessage.warning('请先选择要删除的公告');
    return;
  }

  try {
    const confirm = await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedAnnouncements.value.length} 条公告吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    if (confirm !== 'confirm') return;

    // 调用API批量删除
    await request.post('/announcement/batchDelete', {
      ids: selectedAnnouncements.value
    });

    // 更新本地状态
    messageItemStore.allAnnReceivers = messageItemStore.allAnnReceivers.filter(
        ann => !selectedAnnouncements.value.includes(ann.id)
    );

    ElMessage.success(`成功删除 ${selectedAnnouncements.value.length} 条公告`);

    // 清空选中状态
    selectedAnnouncements.value = [];
  } catch (error) {
    console.error('批量删除失败', error);
    ElMessage.error('删除失败，请重试');
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 搜索后回到第一页
  loadAnnouncements();
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  currentPage.value = 1;
  loadAnnouncements();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};


// 生命周期钩子
onMounted(() => {
  // 初始加载公告数据
  loadAnnouncements();

});
</script>

<style scoped>
.announcement-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table__row.unread {
  background-color: #f5f9ff !important;
}

.el-table__row.unread:hover {
  background-color: #e6f2ff !important;
}
</style>